package com.promise.jokerdream.work.signin.after

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 黄历工作
class CalendarWork(uin: String): BaseWork(uin) {

    override val name: String
        get() = "黄历"

    override val priority: Int
        get() = 9

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        try {
            // 1. 查询黄历信息
            val queryResult = gameApi.queryCalendar()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // taskStatus为1才领奖
                    if (response.taskStatus == 1) {
                        val rewardResult = gameApi.getCalendarReward()
                        rewardResult.foldWithApiException(
                            onSuccess = { rewardResponse ->
                                historyManager.addHistory(name, rewardResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )

            // 2. 查询占卜信息
            val fateQueryResult = gameApi.queryCalendarFate()
            fateQueryResult.foldWithApiException(
                onSuccess = { fateResponse ->
                    // num>0才占卜
                    if (fateResponse.num > 0 && fateResponse.fate.isEmpty()) {
                        val fateResult = gameApi.divinationCalendar()
                        fateResult.foldWithApiException(
                            onSuccess = { fateResponse ->
                                historyManager.addHistory(name, fateResponse.getDescription())
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                }
            )

            return WorkResult.Success
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            return WorkResult.Failure(e, e.message)
        }
    }
}